<template>
  <el-dialog
    v-el-drag-dialog
    title="初始化"
    :visible.sync="visible"
    width="900px"
    append-to-body
    @close="reset"
  >
    <div style="width: 100%;">
      <el-form class="form" :model="form" label-width="90px" label-position="left">
        <el-row>
          <el-col v-if="userInfo.showRN === JINJIANG" :span="7">
            <el-form-item label="选择机构:">
              <el-tree-select
                v-model="form.orgId"
                :clearable="true"
                class="tree-select"
                :popover-width="360"
                :select-params="{
                  clearable: true,
                  placeholder: '请选择',
                }"
                :tree-params=" {
                  'expand-on-click-node': false,
                  'highlight-current': true,
                  props:{
                    value:'orgId',
                    label: 'orgName',
                    disabled: 'disabled',
                  },
                  data: treeData
                }"
                @node-click="selectTreeChange"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="userInfo.showRN === JINJIANG" :span="7">
            <el-form-item label="规格型号:">
              <el-select
                v-model="form.specCode"
                style="width: 100%;"
                placeholder="请选择"
              >
                <el-option
                  v-for="(l, i) in goodsTypesDetailList"
                  :key="i"
                  :value="l.specCode"
                  :label="l.specName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="气瓶编号：">
              <el-input v-model.trim="form.num" style="width: 100%;" class="input" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label-width="10px">
              <el-button type="primary" class="btn" @click="add">添加</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="tip">*请查明原因后谨慎使用此功能，否则将会导致报表不准确!</div>
      <el-table :data="tableData" max-height="400" style="width: 100%;">
        <el-table-column v-if="userInfo.showRN === JINJIANG" prop="orgId" label="选择机构" width="280">
          <template slot-scope="scope">
            <div>
              <!-- <el-input v-if="scope.row.isEdit" v-model="scope.row.specCode" /> -->
              <el-tree-select
                v-if="scope.row.isEdit"
                v-model="scope.row.editingValues.orgId"
                :clearable="false"
                class="tree-select"
                :popover-width="360"
                :select-params="{
                  placeholder: '请选择',
                }"
                :tree-params=" {
                  'expand-on-click-node': false,
                  'highlight-current': true,
                  props:{
                    value:'orgId',
                    label: 'orgName',
                    disabled: 'disabled',
                  },
                  data: treeData
                }"
                @node-click="(value) => selectTreeChange1(scope.row, value)"
              />
              <span v-else>{{ scope.row.orgName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="userInfo.showRN === JINJIANG" prop="specCode" label="型号">
          <template slot-scope="scope">
            <div>
              <!-- <el-input v-if="scope.row.isEdit" v-model="scope.row.specCode" /> -->
              <el-select
                v-if="scope.row.isEdit"
                v-model="scope.row.editingValues.specCode"
                style="width: 100%;"
                placeholder="请选择"
                @change="handleChangeSpecCode(scope.row)"
              >
                <el-option
                  v-for="(l, i) in goodsTypesDetailList"
                  :key="i"
                  :value="l.specCode"
                  :label="l.specName"
                />
              </el-select>
              <span v-else>{{ scope.row.specName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="气瓶编号">
          <template slot-scope="scope">
            <div>
              <el-input v-if="scope.row.isEdit" v-model="scope.row.editingValues.num" />
              <span v-else>{{ scope.row.num }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div v-if="scope.row.isEdit">
              <span class="link" @click="saveRow(scope.row, scope.$index)">保存</span>
              <span class="link" @click="cancelEdit(scope.row, scope.$index)">取消</span>
            </div>
            <div v-else>
              <span class="link" @click="editRow(scope.row, scope.$index)">编辑</span>
              <span class="link" @click="deleteRow(scope.$index)">删除</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="reset">取 消</el-button>
      <el-button type="primary" :loading="$loadingPlugin.save" @click="save">提 交</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { batchReleaseBottle, invenQuerySpec } from '@/api'
  import { mapGetters } from 'vuex'

  const JINJIANG = 58 // 晋江城市标识

  export default {
    name: 'realseBottle',
    props: {
      treeData: {
        type: Array,
        require: true
      }
    },
    data() {
      return {
        JINJIANG,
        visible: false,
        form: {
          num: '',
          specCode: ''
        },
        tableData: [],
        goodsTypesDetailList: []
      }
    },
    computed: {
      ...mapGetters([
        'userInfo'
      ])
    },
    created() {
      this.getTypeList()
    },
    methods: {
      async open() {
        return new Promise(async(resolve) => {
          this.visible = true
        })
      },
      async getTypeList() {
        const res = await invenQuerySpec({})
        this.goodsTypesDetailList = res.data
      },
      add() {
        if (this.userInfo.showRN === JINJIANG) {
          if (!this.form.orgId) {
            this.$message.warning('请选择机构')
            return
          }
          if (!this.form.specCode) {
            this.$message.warning('请选择规格型号')
            return
          }
        }

        // 检查是否存在相同的机构、规格型号、气瓶编号组合
        const duplicate = this.tableData.some((data, i) =>
          data.orgId === this.form.orgId && data.specCode === this.form.specCode && data.num === this.form.num
        )
        if (duplicate) {
          this.$message.warning('您已添加该气瓶！')
          return
        }
        const spec = this.goodsTypesDetailList.find(item => item.specCode === this.form.specCode)
        if (this.form.num) {
          this.tableData.push({
            num: this.form.num,
            specCode: this.form.specCode,
            specName: spec ? spec.specName : '',
            orgId: this.form.orgId,
            orgName: this.form.orgName,
            orgSNNo: this.form.orgSNNo,
            isEdit: false,
            editingValues: {
              num: this.form.num,
              specCode: this.form.specCode,
              specName: spec ? spec.specName : '',
              orgId: this.form.orgId,
              orgName: this.form.orgName,
              orgSNNo: this.form.orgSNNo
            } // 保存编辑的值
          })
          this.form.num = ''
        } else {
          this.$message.warning('气瓶编号不能为空')
        }
      },
      editRow(row) {
        row.isEdit = true
      },
      saveRow(row, index) {
        if (!row.editingValues.num.trim()) {
          this.$message.warning('气瓶编码不能为空')
          return
        }
        // 检查是否存在相同的机构、规格型号、气瓶编号组合
        const duplicate = this.tableData.some((data, i) =>
          data.orgId === row.editingValues.orgId && data.specCode === row.editingValues.specCode && data.num === row.editingValues.num && i !== index
        )
        if (duplicate) {
          this.$message.warning('保存失败，已存在相同的气瓶')
          return
        }
        this.$set(this.tableData, index, { ...row, ...row.editingValues })
        this.tableData[index].isEdit = false
      },
      cancelEdit(row) {
        row.editingValues = {
          num: row.num,
          specCode: row.specCode,
          specName: row.specName,
          orgId: row.orgId,
          orgName: row.orgName,
          orgSNNo: row.orgSNNo
        } // 恢复成原始值
        row.isEdit = false // 退出编辑模式
      },
      deleteRow(index) {
        this.tableData.splice(index, 1)
      },
      async save() {
        if (this.tableData.length > 0) {
          // const f1 = this.tableData.every(item => item.specCode)
          const f2 = this.tableData.every(item => item.num)
          const f3 = this.tableData.some(item => item.isEdit)
          if (f3) {
            this.$message.warning('请完成所有编辑后再提交')
            return
          }
          // if (!f1) {
          //   this.$message.warning('规格型号不能为空')
          //   return
          // }
          if (f2) {
            const params = this.tableData.map((item) => ({
              orgId: item.orgId || undefined,
              orgName: item.orgName || undefined,
              orgSNNo: item.orgSNNo || undefined,
              specName: item.specName || undefined,
              specCode: item.specCode || undefined,
              bottleCode: item.num
            }))
            const res = await batchReleaseBottle(params)
            if (res.data) {
              this.$message.success('初始化成功')
              this.visible = false
              this.$emit('upDataTable')
            }
          } else {
            this.$message.warning('气瓶编码不能为空')
          }
        } else {
          this.$message.warning('请添加气瓶编码')
        }
      },
      reset() {
        this.form.num = ''
        this.form.specCode = ''
        this.form.orgId = ''
        this.form.orgName = ''
        this.form.orgSNNo = ''
        this.tableData = []
        this.visible = false
      },
      // 选择机构
      async selectTreeChange(value) {
        this.form.orgName = value.orgName
        this.form.orgSNNo = value.orgSNNo
      },
      // 选择机构
      async selectTreeChange1(row, value) {
        row.editingValues.orgName = value.orgName
        row.editingValues.orgSNNo = value.orgSNNo
      },

      handleChangeSpecCode(row) {
        const findItem = this.goodsTypesDetailList.find(item => item.specCode === row.specCode)
        row.specName = findItem ? findItem.specName : ''
      }
    }
  }
</script>

<style lang="scss" scoped>
  .row {
    display: flex;
    height: 30px;
    margin-bottom: 10px;
    line-height: 30px;
    .label {
      width: 120px;
    }
    .input {
      width: 180px;
    }
    .btn {
      margin-left: 10px;
    }
  }
  .link {
    margin-right: 10px;
    color: $themeColor;
    cursor: pointer;
  }
  .tip {
    margin-bottom: 10px;
    color: #F56C6C;
  }
</style>
